package com.lakala.sh.bps.bpsmerchant.client.utils;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: peijian
 * @date: 2019/11/22 15:53
 */
public class HttpClientUtil {

    private static final String encoding = "UTF-8";

    private static final String JSON_CONTENT_TYPE = "application/json";

    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static HttpClientBuilder httpBuilder = null;
    private static RequestConfig requestConfig = null;

    private static int MAXCONNECTION = 10;

    private static int DEFAULTMAXCONNECTION = 5;

    static {
        //设置http的状态参数
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();

        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(MAXCONNECTION);//客户端总并行链接最大数
        connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);//每个主机的最大并行链接数
        httpBuilder = HttpClients.custom();
        httpBuilder.setConnectionManager(connectionManager);
    }

    /**
     * 带K-V形式参数的GET请求
     * @param url
     * @param params
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doGet(String url, Map<String, Object> params) throws ClientProtocolException, IOException {
        return doGet(url, params, new HashMap<String, String>());
    }

    public String doGet(String url, Map<String, Object> params, Map<String, String> headers) throws ClientProtocolException, IOException {
        StringBuffer param = new StringBuffer();
        int i = 0;
        for (String key : params.keySet()) {
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }
            param.append(key).append("=").append(params.get(key));
            i++;
        }
        url += param;
        String result = null;
        HttpClient httpclient = getConnection();
        HttpGet httpGet = new HttpGet(url);

        for(Map.Entry<String, String> entry : headers.entrySet()) {
            httpGet.addHeader(entry.getKey(), entry.getValue());
        }
        HttpResponse response = httpclient.execute(httpGet);
        InputStream in = response.getEntity().getContent();
        result = IOUtils.toString(in, encoding);
        in.close();	//in.close()作用是将用完的连接释放，下次请求可以复用。如果是response.close();结果就是连接会被关闭，并且不能被复用
        return result;
    }

    /**
     * 带K-V形式参数的POST请求
     * @param url API接口URL
     * @param params 参数map
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doPost(String url, Map<String, Object> params) throws ClientProtocolException, IOException {
        HttpClient httpclient = getConnection();
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = null;
        httpPost.setConfig(requestConfig);
        List<NameValuePair> pairList = new ArrayList<>(params.size());
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
                    .getValue().toString());
            pairList.add(pair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(encoding)));
        response = httpclient.execute(httpPost);

        InputStream in = response.getEntity().getContent();
        result = IOUtils.toString(in, encoding);
        in.close();	//in.close()作用是将用完的连接释放，下次请求可以复用。如果是response.close();结果就是连接会被关闭，并且不能被复用
        return result;
    }

    /**
     * 带JSON形式参数的POST请求,默认content-type:application/json
     * @param url
     * @param json json对象
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String doPostByJson(String url, Object json) throws ClientProtocolException, IOException {
        return doPostByJson(url,json,JSON_CONTENT_TYPE);
    }

    /**
     * 带JSON形式参数的POST请求
     * @param url
     * @param json json对象
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String doPostByJson(String url, Object json,String contentType) throws ClientProtocolException, IOException {
        return doPostByJson(url, json, contentType, new HashMap<>());
    }

    public static String doPostByJson(String url, Object json,String contentType, Map<String, String> headers) throws ClientProtocolException, IOException {
        HttpClient httpclient = getConnection();
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = null;
        httpPost.setConfig(requestConfig);
        StringEntity stringEntity = new StringEntity(json.toString(), encoding);
        stringEntity.setContentEncoding(encoding);
        stringEntity.setContentType(contentType);
        httpPost.setEntity(stringEntity);

        for(Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        response = httpclient.execute(httpPost);
        InputStream in = response.getEntity().getContent();
        result = IOUtils.toString(in, encoding);
        in.close();	//in.close()作用是将用完的连接释放，下次请求可以复用。如果是response.close();结果就是连接会被关闭，并且不能被复用
        return result;
    }

    /**
     * 不带参数的GET
     * @param url
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doGet(String url) throws ClientProtocolException, IOException {
        return doGet(url, new HashMap<String, Object>());
    }

    /**
     * 不带参数的POST请求
     * @param url
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doPost(String url) throws ClientProtocolException, IOException {
        return doPost(url, new HashMap<String, Object>());
    }

    public String doPostByJson(String url, Object json, Map<String, String> headers) throws ClientProtocolException, IOException {
        String result = doPostByJson(url, json, JSON_CONTENT_TYPE, headers);
        return result;
    }


    private static CloseableHttpClient getConnection() {
        CloseableHttpClient httpClient = httpBuilder.build();
        return httpClient;
    }

}
